// image-conversion插件：https://developer.aliyun.com/mirror/npm/package/image-conversion
import * as imageConversion from 'image-conversion';

/**
 * 将图片压缩到指定size
 * @param {file} file 
 * @param {number} size (kb)
 */
const compressToSize = function (file, size) {
    const accuracy = 0.95;      // 精度范围(0.8~0.99)，压缩尺寸会在这个百分比范围左右浮动，所以如果要小于指定尺寸，需要计算该值的影响
    const newSize = size - size * (1 - accuracy)  * 2;    // 压缩后的尺寸会左右浮动，那么在期望值的基础上减去可能会浮动的最大值(不是很准确故*2以避免接口报错)，最终输出结果将不会大于期望值
    console.log(newSize, 12);
    return imageConversion.compressAccurately(file, {size: newSize, accuracy});
}

/**
 * 压缩图片至指定质量
 * @param {file} file 
 * @param {string} quality 
 */
const compressToQuality = function (file, quality) {
    return imageConversion.compress(file, quality);
}

/**
 * base64转file
 * @param {string} dataURL 
 * @param {string} type 
 */
const dataURLtoBolb = function (dataURL, type = "image / png") {
    return imageConversion.dataURLtoFile(dataURL, type);
}

/**
 * 将File（Blob）对象转换为dataURL字符串。
 * @param {string} file 
 */
const filetoDataURL = function (file) {
    return imageConversion.filetoDataURL(file);
}

/**
 * 下载图片
 * @param {string} file 
 * @param {string} fileName 
 */
const downloadFile = function (file, fileName) {
    return imageConversion.downloadFile(file, fileName);
}

const bolbToFile = function (blob, fileName = '') {
    return new Promise((resolve, reject) => {
        const file = new window.File([blob], fileName, {type: 'image/png'});
        resolve(file);
    })
}

export {
    compressToSize,
    compressToQuality,
    dataURLtoBolb,
    filetoDataURL,
    downloadFile,
    bolbToFile
}